package com.std.getstuffdone;

import models.Utility;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.graphics.Color;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

/**
 * This is an activity that allows users to enter information about a 
 * task, which is required for creating a new task and editing a task
 * The information entered is passed back to the calling activity (PlanningScreenActivity)
 * 
 * @author Team STD
 *
 */
public class EnterTaskInfo extends Activity {
	// UI buttons for setting and clearing a start time
	private Button mPickTime;
	private Button mClearTime;
	private Button mSaveTask;
	
	// UI Edit Text boxes
	private EditText titleEditTxt;
	private EditText durationEditTxt;
	private EditText travelTimeEditTxt;
	private Spinner prioritySpinner;
	
	// startTime hours and minutes
	private int mHour;
	private int mMinute;
	
	// store user input information
	private Long taskId;
	private String title;
	private String startTime;
	private int duration;
	private int travelTime;
	private int priority;
	
	// the background associated with the EditText boxes when Activity first displayed
	private Drawable origTitleEditTxt;
	private Drawable origDurationEditTxt;
	private Drawable origTravelTimeEditTxt;
	
	// flag to determine whether task editing is to be performed on screen
	private boolean createNewTask;
			
	static final int TIME_DIALOG_ID = 0;
	protected static final String LOG = "ENTER_TASK_INFO";

	
	// this method is called every time the activity is created
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.entertaskinfo);
				
		 // set handlers to the buttons and views
	    setHandlers();
		
		// add a click listeners to the buttons
		setButtonListeners();
		setEditTextListeners();
		setSpinnerListeners();
		
		// get information passed from calling activity
		Bundle bundle = this.getIntent().getExtras();
		createNewTask = bundle.getBoolean(Utility.BUNDLE_NEW_TASK_FLAG);
		if(!createNewTask){
			// edit task
			taskId = bundle.getLong(Utility.BUNDLE_TASK_ID);
			setEditableTaskInfo(bundle);
		}
	}
	
	/**
	 * This method display information of the task to be edited in the form
	 * @param bundle containing information of task to display in the form
	 */
	private void setEditableTaskInfo(Bundle bundle) {
		titleEditTxt.setText(bundle.getString(Utility.BUNDLE_TASK_TITLE));
		mPickTime.setText(bundle.getString(Utility.BUNDLE_TASK_START_TIME));
		durationEditTxt.setText(bundle.getString(Utility.BUNDLE_TASK_DURATION));
		travelTimeEditTxt.setText(bundle.getString(Utility.BUNDLE_TASK_TRAVEL_TIME));
		prioritySpinner.setSelection(bundle.getInt(Utility.BUNDLE_TASK_PRIORITY));
		
		String startTime = bundle.getString(Utility.BUNDLE_TASK_START_TIME);
		Log.d("StartTime = ", startTime);
		if(!startTime.equalsIgnoreCase("Set start time")){
			mHour = Integer.parseInt(startTime.substring(0, 2));
			mMinute =  Integer.parseInt(startTime.substring(3,  5));
		}
	}

	// Set handlers to UI elements
	private void setHandlers() {
		mPickTime = (Button) findViewById(R.id.changeStartTimeButton);
		mClearTime = (Button) findViewById(R.id.clearStartTimeButton);
		mSaveTask = (Button) findViewById(R.id.saveTask);
		
		titleEditTxt = (EditText)findViewById(R.id.taskTitle);
		durationEditTxt = (EditText)findViewById(R.id.taskDuration);
		travelTimeEditTxt = (EditText)findViewById(R.id.taskTravelTime);
		prioritySpinner = (Spinner)findViewById(R.id.taskPriority);
		
		origTitleEditTxt = titleEditTxt.getBackground();
		origDurationEditTxt = durationEditTxt.getBackground();
		origTravelTimeEditTxt = travelTimeEditTxt.getBackground();
	}

	//This method sets the listener for the priority selection spinner
	private void setSpinnerListeners() {
		prioritySpinner.setOnItemSelectedListener(new PrioritySelectionListener());
	}
	
	// This method sets listeners to the Edit Text boxes
	private void setEditTextListeners() {
		
		titleEditTxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
		    public void onFocusChange(View v, boolean hasFocus) {
		    	if(hasFocus) {
		        	titleEditTxt.setBackgroundDrawable(origTitleEditTxt);
		        }
		    }
		});
		
		durationEditTxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
		    public void onFocusChange(View v, boolean hasFocus) {
		    	if(hasFocus) {
		        	durationEditTxt.setBackgroundDrawable(origDurationEditTxt);
		        }
		    }
		});
		
		travelTimeEditTxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
		    public void onFocusChange(View v, boolean hasFocus) {
		    	if(hasFocus) {
		        	travelTimeEditTxt.setBackgroundDrawable(origTravelTimeEditTxt);
		        }
		    }
		});
	}
	
	// This method sets listeners to the UI buttons
	private void setButtonListeners() {
		
		// displays time picker dialog
		mPickTime.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
            }
        });
        
        mClearTime.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				mHour = -1;
				mMinute = -1;
				mPickTime.setText("Set start time");
			}
		});

        // validates user input, transmit saved information to calling activity
        mSaveTask.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// get entered information and validate
				// if validation fails returns false, otherwise returns true
				boolean isValid = validateInput();
				
				if(isValid) {
					// information entered is valid, so save the information
					getFormInfo();
					Bundle bundle = getTaskInfoBundle();
					Intent intent = new Intent();
					intent.putExtras(bundle);
					if(createNewTask) {
						setResult(Utility.RETURN_CODE_NEW_TASK_INFO, intent);
					}
					else {
						setResult(Utility.RETURN_CODE_EDIT_TASK_INFO, intent);
					}
					finish();
				} else {
					// information not valid, so do nothing
				}
			}

			// This method fills a Bundle with the task information entered by the user 
			// @return Bundle containing task info entered by user
			private Bundle getTaskInfoBundle() {
				
				// enter user entered information in bundle
				Bundle bundle = new Bundle();
				if(!createNewTask){
					bundle.putLong(Utility.BUNDLE_TASK_ID, taskId);
				}
				bundle.putString(Utility.BUNDLE_TASK_TITLE, title);
				bundle.putString(Utility.BUNDLE_TASK_START_TIME, startTime);
				bundle.putInt(Utility.BUNDLE_TASK_DURATION, duration);
				bundle.putInt(Utility.BUNDLE_TASK_TRAVEL_TIME, travelTime);
				bundle.putInt(Utility.BUNDLE_TASK_PRIORITY, priority);
				return bundle;
			}
		});
	}
	
	
	// this method validates the user input
	// if input is invalid, highlights the invalid input Edit Text boxes in red, and returns false
	// if input is valid, returns true
	private boolean validateInput(){
		// get user entered text
		String titleTmp = titleEditTxt.getText().toString();
		String durationTmp = durationEditTxt.getText().toString();
		String travelTimeTmp = travelTimeEditTxt.getText().toString();
				
		boolean isValid = true;
				
		// validate task title		
		if(titleTmp.equalsIgnoreCase("")){
			titleEditTxt.setBackgroundColor(Color.RED);
			isValid = false;
		}
				
		// validate  task duration
		if(durationTmp.equalsIgnoreCase("")) {
			durationEditTxt.setBackgroundColor(Color.RED);
			isValid = false;
		}
		else {
			int durationTmpInt = Integer.valueOf(durationTmp);
			if(durationTmpInt <= 0 || durationTmpInt > Utility.MAX_TASK_DURATION) {
				durationEditTxt.setBackgroundColor(Color.RED);
				isValid = false;
			}
		}
				
		// validate task travel time
		if(travelTimeTmp.equalsIgnoreCase("")) {
			travelTimeEditTxt.setBackgroundColor(Color.RED);
			isValid = false;
		}
		else {
			int travelTimeTmpInt = Integer.valueOf(travelTimeTmp);
			if(travelTimeTmpInt < 0 || travelTimeTmpInt > Utility.MAX_TRAVEL_TIME) {
				travelTimeEditTxt.setBackgroundColor(Color.RED);
				isValid = false;
			}
		}
		
		return isValid;
		
	}

	// get information entered by user
	// assumes that the information is already validated by calling  validateInput()
	private void getFormInfo(){
		
		// get user entered text
		title = titleEditTxt.getText().toString();
		
		startTime = mPickTime.getText().toString();
		if(startTime.equalsIgnoreCase("Set start time")) {
			startTime = null;
		}
		
		duration = Integer.valueOf(durationEditTxt.getText().toString());
		travelTime = Integer.valueOf(travelTimeEditTxt.getText().toString());
				
	}
	

	// Creates a new pop-up dialog to enter the start time
	// @return Dialog to enter start time
	@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case TIME_DIALOG_ID:
        	//TimePickerDialog timeDialog = new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, false);
        	
           return new TimePickerDialog(this,
                  mTimeSetListener, mHour, mMinute, false);
        }
        return null;
    }
	
	//Updates the start time displayed on the mPickTime button
	private void updateDisplay() {
        mPickTime.setText(
            new StringBuilder()
                    .append(pad(mHour)).append(":")
                    .append(pad(mMinute)));
    }
   
    // Handles callback received when the user "sets" the time in the dialog
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {
      public void onTimeSet(android.widget.TimePicker view, int hourOfDay, int minute) {
                mHour = hourOfDay;
                mMinute = minute;
                updateDisplay();
            }
      };
      
      private static String pad(int c) {
          if (c >= 10)
              return String.valueOf(c);
          else
              return "0" + String.valueOf(c);
      }

      /**
       * Finishes the activity when back button is pressed
       */
      @Override
      public void onBackPressed(){
    	  Intent in = new Intent();
    	  setResult(Utility.RETURN_CODE_CANCEL, in);
    	  finish();
      }
      
      // inner class which implements listener for prioritySpinner
      private class PrioritySelectionListener implements OnItemSelectedListener {
    	
	    	// gets the priority from spinner when one is selected  
			public void onItemSelected(AdapterView<?> parent, View view, int pos,
					long id) {
				String selected = parent.getItemAtPosition(pos).toString();
				priority = Utility.getPriorityInt(selected);
			}
			
			// gets the default priority frm spinner when nothing is selected
			public void onNothingSelected(AdapterView<?> parent) {
				String selected = parent.getItemAtPosition(0).toString();
				priority = Utility.getPriorityInt(selected);
			}
      }
}
